package com.apes.framework.condition;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.Connector;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.query.lib.JPAConditionQuery;
import com.apes.framework.query.lib.PubToolUtil;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.MapUtil;
import com.apes.scm.rbac.model.User;
import com.apestech.api.condition.ConditionExec;
import com.apestech.api.condition.ConditionStrategyExec;
import com.apestech.api.xml.esb.EsbUtil;
import com.apestech.api.xml.esb.modul.EsbForm;
import com.apestech.formwork.condition.ConditionUtil;
import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.pinyin.PinyinConverter;
import com.apestech.framework.sql.ReportSql;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.xml.condition.modul.Condition;
import com.apestech.framework.xml.condition.modul.Dimension;
import com.apestech.framework.xml.plugin.modul.SysCondition;
import com.apestech.framework.xml.table.modul.Tables;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author hup
 * @create 2019-08-29-9:36
 */
@Service("strategyService")
public class StrategyService extends PubToolUtil {
    @Autowired
    Connector connector;
    private String sBusinessType = "ConditionStrategy";
    private String sBusinessType_imp = "ConditionStrategyImport";
    private String sBusinessType_stop = "ConditionStrategyStop";

    public JSONObject getCondition(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            JSONObject map=new JSONObject();
            String key=json.getString("key");
            if(key==null && json.get("condition")!=null){
                JSONObject m=JSON.toJSONArray(json.get("condition")).get(0);
                if(m!=null) {
                    key=m.getString("value");
                }
            }
            map.put("content", ConditionUtil.getCondition(session, key, json));
            map.put("pages",1);
            map.put("page",0);
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getConditionUsed(SimpleRequest param) throws RuntimeException {
        try {
            if(param.getSession()==null){
                throw new RuntimeException("当前用户信息已经发生变更，请重新刷新系统！");
            }
            JSONObject json= getInput(param);
            json=PubToolUtil.getAssociateJson(json);
            String key=json.getString("key");
            SqlSession session=getSession(connector.getConnection());
            json.put("POSTID", param.getSession().getPostId());
            JSONObject map=new JSONObject();
            //map.put("content", ConditionUtil.getConditionUsed(session, key, json));
            map.put("content", ConditionUtil.getConditionFromDb(session, json));
            map.put("pages",1);
            map.put("page",0);
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getConditionDimension(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            json=PubToolUtil.getAssociateJson(json);
            String id=json.getString("ID");
            if(id==null){
                return null;
            }
            Condition con= ConditionUtil.getCondition(id, session);
            con.getTables();
            JSONArray list=new JSONArray();
            ArrayList<Dimension> dlist=con.getDimension();
            int len=dlist.size();
            for(int i=0; i<len; i++){
                Dimension dimension=dlist.get(i);
                JSONObject m=new JSONObject();
                m.put("ID", dimension.getId());
                m.put("id", dimension.getId());
                m.put("FIELD", dimension.getFieldKey().replace(",","/"));
                m.put("NAME", dimension.getName());
                m.put("NAME_PY", new PinyinConverter().getPinyin(m.getString("NAME")));
                list.add(m);
            }
            JSONObject map=new JSONObject();
            map.put("content", list);
            map.put("pages",1);
            map.put("page",0);
            map.put("tag",con.getTag());
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getConditionDimensionUsed(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            json=PubToolUtil.getAssociateJson(json);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            String key=json.getString("key");
            if(id==null){
                return null;
            }
            Condition con= ConditionUtil.getCondition(id, session);
            JSONArray list=new JSONArray();
            ArrayList<Dimension> dlist=con.getDimension();
            int len=dlist.size();
            for(int i=0; i<len; i++){
                if(session.tableExists(con.getTableKey().getTabName(dlist.get(i).getId()))){
                    Dimension dimension=dlist.get(i);
                    String py=new PinyinConverter().getPinyinAbbr(dimension.getName());
                    boolean flag=(key==null || (dimension.getId().toLowerCase().indexOf(key)>=0 || (dimension.getName().toLowerCase().indexOf(key)>=0 || (py.toLowerCase().indexOf(key)>=0) )));
                    if(flag){
                        JSONObject m=new JSONObject();
                        m.put("ID", dimension.getId());
                        m.put("id", dimension.getId());
                        m.put("FIELD", dimension.getFieldKey().replace(",","/"));
                        m.put("NAME", dimension.getName());
                        m.put("NAME_PY", new PinyinConverter().getPinyin(m.getString("NAME")));
                        list.add(m);
                    }
                }
            }
            JSONObject map=new JSONObject();
            map.put("content", list);
            map.put("pages",1);
            map.put("page",0);
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONArray getDetail(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            Condition con= ConditionUtil.getCondition(id, session);
            con.getTables();
            JSONArray list=new JSONArray();
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*--获取界面相关--*/
    public JSONObject getFormField(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            String mid=json.getString("MID");
            Condition con= ConditionUtil.getCondition(id, session);
            EsbForm form=new EsbForm();
            form.setSession(session);
            JSONObject fieldJson=new JSONObject();
            JSONArray list=form.getConditionField(con, mid, fieldJson);
            JSONObject r=new JSONObject();
            r.put("control", list);
            r.put("form_default", fieldJson.get("form_default"));
            r.put("detail_default", fieldJson.get("detail_default"));
            return r;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getImpFormField(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            String mid=json.getString("MID");
            Condition con= ConditionUtil.getCondition(id, session);
            EsbForm form=new EsbForm();
            form.setSession(session);
            JSONObject fieldJson=new JSONObject();
            JSONArray list=form.getImportConditionField(con, mid, fieldJson);
            JSONObject r=new JSONObject();
            r.put("control", list);
            r.put("form_default", fieldJson.get("form_default"));
            r.put("detail_default", fieldJson.get("detail_default"));
            return r;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getStopFormField(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            String mid=json.getString("MID");
            Condition con= ConditionUtil.getCondition(id, session);
            EsbForm form=new EsbForm();
            form.setSession(session);
            JSONObject out=new JSONObject();
            JSONArray list=form.getStopConditionField(con, mid, out);
            JSONObject r=new JSONObject();
            r.put("control", list);
            r.put("form_default", out.get("form_default"));
            r.put("detail_default", out.get("detail_default"));
            return r;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getFormField_qry(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            String mid=json.getString("MID");
            Condition con= ConditionUtil.getCondition(id, session);
            EsbForm form=new EsbForm();
            form.setSession(session);
            JSONObject fieldJson=new JSONObject();
            return form.getQryConditionField(con, mid, json, fieldJson);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /*--获取界面相关--*/

    public JSONObject getDownData(SimpleRequest param) throws RuntimeException {
        try {
            String field=null;
            JSONObject json= getInput(param);
            field=json.getString("sysField");
            JSONObject m=new JSONObject();
            JSONArray list=EsbUtil.getDownData(field);
            if(list==null){
                SqlSession session=getSession(connector.getConnection());
                String remark=null;
                if("STOP_STATE".equals(field)){
                    remark="状态(sent:新建;exec:终止)";
                } else if("IMP_STATE".equals(field)) {
                    remark = "状态(sent:新建;exec:生成策略单号)";
                } else {
                    session.getColumnRemark(field, null);
                }
                ArrayList<ArrayList<String>> mlist = StringUtil.getStrSplitList("; :", getSplitList(remark));
                EsbUtil.setDownData(field, mlist);
                list=EsbUtil.getDownData(field);
            }
            m.put("content", list);
            m.put("page",0);
            return m;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*--策略调整单相关--*/
    public void createTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            ConditionExec exec=new ConditionExec(session, cid);
            exec.createTable(false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject saveTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            String sBZ = "创建";
            old.putAll(json);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("STATE","sent");
            json.put("UPDATER_ID", param.getPersonId());
            json.put("CREATE_DATE", "SYSDATE");
            json.put("UPDATE_DATE", "SYSDATE");
            json.put("START_DATE", DateUtil.getStartDate(json.getString("START_DATE")));
            json.put("END_DATE", DateUtil.getEndDate(json.getString("END_DATE")));
            if(id==null) json.put("LAST_UPDATED_STAMP", "SYSDATE");
            else json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            String tabname=exec.getCondition().getTableKey().getTabName(mid);
            String tab=tabname+"_ITEM";
            json.put(tab, json.get("ITEMS"));
            json.remove("ITEMS");

            if (id != null) sBZ = "编辑";

//            String sid=exec.saveTable(mid, json, new ConSaveInter(session), new JPAId(cid, exec.getCondition().getSeqlist(), session));
            String sid=exec.saveTable(mid, json, new ConSaveInter(session), null);
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType, "businessKey", cid+'.'+mid+'.'+sid, "operate", sBZ,
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return queryId(session, exec, mid, tabname, sid, param.getPostId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject execTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("APPROVE_UID_ID", param.getPersonId());
            ConditionExec exec=new ConditionExec(session, cid);
            String tabname=exec.getCondition().getTableKey().getTabName(mid);
            String tab=tabname+"_ITEM";
            json.put(tab, json.get("ITEMS"));
            json.remove("ITEMS");
            exec.execTableByM(id, mid, param.getPersonId());
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType, "businessKey", cid+'.'+mid+'.'+id, "operate", "执行",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return queryId(session, exec, mid, tabname, id, param.getPostId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject stopTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            ConditionExec exec=new ConditionExec(session, cid);
            String tabname=exec.getCondition().getTableKey().getTabName(mid);
            exec.stopTableByM(id, mid, param.getPersonId());
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType, "businessKey", cid+'.'+mid+'.'+id, "operate", "终止",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return queryId(session, exec, mid, tabname, id, param.getPostId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String deleteTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            exec.deleteTableByM(id, mid);
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType, "businessKey", cid+'.'+mid+'.'+id, "operate", "删除",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return "删除成功";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject queryTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            String id=json.getString("ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            ConditionExec exec=new ConditionExec(session, cid);
            String tabname=exec.getCondition().getTableKey().getTabName(mid);
            JSONObject r=queryId(session, exec, mid, tabname, id, param.getPostId());
            return r;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //策略制单专用
    public JSONObject getConFromId(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            if(json.get("ID")==null){
                json.put("ID", json.get("id"));
            }
            JSONArray list=session.getForJSON().query("SELECT A.ID, A.CONDITION_ID, A.DIMENSION_ID, A.B_ID FROM EXE_CONDITION_SUM A WHERE 1=1 AND ID=#{ID} ", json);
            if(list.size()==0) return null;
            JSONObject map=list.get(0);
            String cid=map.getString("CONDITION_ID");
            String mid=map.getString("DIMENSION_ID");
            String id=map.getString("B_ID");
            ConditionExec exec=new ConditionExec(session, cid);
            String tabname=exec.getCondition().getTableKey().getTabName(mid);
            JSONObject r=queryId(session, exec, mid, tabname, id, param.getPostId());
            r.put("Z_ID", json.getString("ID"));
            return r;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /*--策略调整单相关--*/

    public JSONObject conditionStrategy(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            SqlSession session=getSession(connector.getConnection());
            ConditionStrategyExec exec=new ConditionStrategyExec(session, json.getString("conditionStrategyId"));
            exec.setInput(json);
            exec.expain();
            return exec.getResultMap();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void report(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            String reportId=json.getString("reportId");
            if(reportId==null){
                throw new RuntimeException("reportId不能为空，请补全！");
            }
            SqlSession session=getSession(connector.getConnection());
            ReportSql report=new ReportSql(session);
            report.execute(reportId,json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private JSONObject getKeyValue(JSONObject old, JSONObject data) throws Exception{
        ArrayList<String> klist=old.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Object vold=old.get(k);
            Object val=data.get(k);
            if(vold instanceof Map && !(val instanceof Map)){
                data.put(k, vold);
            } else if((vold instanceof ArrayList || vold instanceof JSONArray) && (val instanceof ArrayList || val instanceof JSONArray)){
                JSONArray olist= JSON.toJSONArray(vold);
                JSONArray vlist= JSON.toJSONArray(val);
                int olen=olist.size();
                for(int o=0; o<olen; o++){
                    vlist.set(o, getKeyValue(olist.get(o), vlist.get(o)));
                }
                data.put(k, vlist);
            }
            if(val!=null && val instanceof java.sql.Date){
                data.put(k, data.getString(k));
            }
        }
        return data;
    }


    /*--导入相关基础方法--*/
    public JSONObject saveImpTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            old.putAll(json);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("IMP_ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("STATE","sent");
            json.put("UPDATER_ID", json.get("CREATOR_ID"));
            if(id==null) json.put("LAST_UPDATED_STAMP", "SYSDATE");
            else json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            if(id==null){
                JSONArray list=JSON.toJSONArray(json.get("FILES"));
                int len=list.size();
                for(int i=0; i<len; i++){
                    String file= LocalVariable.getTempDir()+list.get(i).getString("name");
                    id=exec.getConOper().getConImport().importXls(mid, file, json);
                    FileUtil.deleteFile(file);
                }
            } else {
                exec.getConOper().getConImport().saveImportXls(mid, json);
            }
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType_imp, "businessKey", id, "operate", "导入数据",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return queryImpTable(session, id, param.getPostId());
            //exec.getConOper().getConImport().queryImport(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String deleteImpTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            old.putAll(json);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("IMP_ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            exec.getConOper().getConImport().deleteImport(mid, json);
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType_imp, "businessKey", id, "operate", "删除导入单",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return "删除成功";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject execImpTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            old.putAll(json);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("IMP_ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            JSONArray dlist= JSON.toJSONArray(json.get("ITEM_F"));
            if(dlist!=null && dlist.size()>0){
                throw new RuntimeException("当前单据还存在[导入错误]页的数据没处理完，不允许做生成策略单号操作！");
            }
            json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            exec.getConOper().getConImport().importSave(mid, json, param.getPersonId());
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType_imp, "businessKey", id, "operate", "生成策略调整单号",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return queryImpTable(session, id, param.getPostId());
            //exec.getConOper().getConImport().queryImport(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject queryImpTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            String id=json.getString("IMP_ID");
            json.put("CID",json.get("CONDITION_ID"));
            json.put("MID",json.get("DIMENSION_ID"));
            SqlSession session=getSession(connector.getConnection());
            return queryImpTable(session, id, param.getPostId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /*--导入相关基础方法--*/


    /*--终止相关基础方法--*/
    public JSONObject saveStopTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            old.putAll(json);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            JSONArray item=JSON.toJSONArray(json.get("item"));
            if(item==null || item.size()==0){
                throw new RuntimeException("请勾选一条及以上对应要终止的明细数据！");
            }
            String id=json.getString("STOP_ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("STATE","sent");
            json.put("UPDATER_ID", json.get("CREATOR_ID"));
            if(id==null) json.put("LAST_UPDATED_STAMP", "SYSDATE");
            else json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            id=exec.getConOper().getConStop().stopSave(mid, json);
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType_stop, "businessKey", id, "operate", "创建终止单",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            JSONObject r=queryStopTable(session, id, param.getPostId());
            return r;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String deleteStopTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            old.putAll(json);
            SqlSession session=getSession(connector.getConnection());
            json=getConId(json, param);
            String id=json.getString("STOP_ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            exec.getConOper().getConStop().deleteStop(mid, json);
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType_stop, "businessKey", id, "operate", "删除终止单",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return "删除成功";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject execStopTab(SimpleRequest param) throws RuntimeException {
        SqlSession session=null;
        try {
            JSONObject json= getInput(param);
            JSONObject old=new JSONObject();
            old.putAll(json);
            Connection connection= connector.getConnection();
            session=getSession(connection);
            json=getConId(json, param);
            String id=json.getString("STOP_ID");
            String cid=json.getString("CID");
            String mid=json.getString("MID");
            json.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP"));
            ConditionExec exec=new ConditionExec(session, cid);
            exec.getConOper().getConStop().execStop(mid, json, param.getPersonId());
            SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                    "businessType", sBusinessType_stop, "businessKey", id, "operate", "执行终止单，将策略执行表数据清除",
                    "workPostName",param.getSession() != null ? param.getSession().getAttribute("workPostName", String.class) : null,
                    "operator_id", ((User)param.getCurrentUser()).getId()));
            return queryStopTable(session, id, param.getPostId());
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public JSONObject queryStopTab(SimpleRequest param) throws RuntimeException {
        try {
            JSONObject json= getInput(param);
            String id=json.getString("ID");
            if(id==null){
                id=json.getString("STOP_ID");
            }
            SqlSession session=getSession(connector.getConnection());
            return queryStopTable(session, id, param.getPostId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private JSONObject queryStopTable(SqlSession session, String stopid, String postId) throws RuntimeException {
        try {
            JSONObject json=new JSONObject();
            json.put("STOP_ID", stopid);
            SysCondition sysCondition=LocalVariable.getConfig().getSysCondition(session);
            String sql="SELECT * FROM EXE_CONDITION_STOP WHERE 1=1 ";
            JSONArray list=session.getForJSON().query(sql, json);

            JSONObject row=list.get(0);
            if(row==null){
                return null;
            }
            row=getDateField(row);
            row=EsbUtil.getConData(row, session, sysCondition);
            row=getDateField(row);
            String cid=row.getString("CONDITION_ID");
            String mid=row.getString("DIMENSION_ID");
            row.remove("CONDITION_ID");
            row.remove("DIMENSION_ID");
            Condition con1= ConditionUtil.getCondition(cid, session);
            json.put("CID", cid);
            json.put("MID", mid);
            ConditionExec exec=new ConditionExec(session, cid);
            String stopTab= exec.getstopTabSql(mid, json);
            sql=stopTab;
            JSONArray slist=new JSONArray();
            session.getForResultSet().sql(sql, json, new QueryCallBackHandler(){
                @Override
                public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                    while(rs.next()){
                        JSONObject mrow=getDateField(rs.toRowJson());
                        mrow=EsbUtil.getConData(mrow, session, sysCondition);
                        slist.add(getDateField(mrow));
                    }
                }
            });
            row.put("productRequireItems", slist);
            JSONObject j=new JSONObject();
            j.put("ID", cid);
            j.put("NAME", con1.getName());
            row.put("EXE_CONDITION", j);
            j=new JSONObject();
            j.put("ID", mid);
            j.put("NAME", con1.getDimensionById(mid).getName());
            row.put("EXE_DIMENSION", j);
            row.put("innerBusinessType", sBusinessType_stop);
            row.put("innerBusinessKey", row.getString("STOP_ID"));
            if(row!=null){
                if(postId!=null){
                    JSONObject map=new JSONObject();
                    map.put("ID", cid);
                    map.put("POSTID", postId);
                    JSONObject out=ConditionUtil.getConditionRole(session, map);
                    if(out!=null){
                        if("1".equals(out.getString("AUT_STOP"))){
                            row.put("sys_stop", "1");
                        }
                    }
                }
            }
            return row;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*--终止相关基础方法--*/

    private JSONObject getConId(JSONObject input, SimpleRequest param) throws Exception {
        SimpleSession session = (SimpleSession) param.getRopRequestContext().getSession();
        if (session != null) {
            input.put("CREATOR_ID", param.getPersonId());
            input.put("UPDATER_ID", param.getPersonId());
            input.put("BELONG_COMPANY_ID", param.getCompanyId());
        }
        return input;
    }

    private JSONObject queryId(SqlSession session, ConditionExec exec, String mid, String tabname, String id, String postId) throws Exception {
        EsbForm esb=new EsbForm();
        esb.setSession(session);
        esb.getConditionFields(exec.getCondition(), mid, null);
        session.setQryConfig(PubToolUtil.getQryConfig(null));
        String cid = exec.getCondition().getId();
        JSONObject json=new JSONObject();
        json.put("CID", cid);
        json.put("CNAME",exec.getCondition().getName());
        json.put("MID", mid);
        json.put("MNAME", exec.getCondition().getDimensionById(mid).getName());
        json.put("ID", id);
        json.put("sysTable", tabname);
        json.put(tabname, exec.getzTabSql_Single(mid, null));  //getzTabSql
        json.put(tabname+"_ITEM", exec.getmxTabSql(mid, null));
        json.put(tabname+"_EXEC", exec.getexecTabSql(mid, null));
        Tables tables=exec.getCondition().getTablesById(tabname);
        JSONObject r=EsbUtil.getTableIsField(tables);
        if(r!=null){
            json.put("SYS_IS_FIELD", r);
        }
        JPAConditionQuery jQuery=new JPAConditionQuery(json, exec, session);
        JSONArray list=session.getForDDL().queryMasterTable(tables, json, jQuery);
        JSONObject data=list.get(0);
        data.put("innerBusinessType", sBusinessType);
        data.put("innerBusinessKey", cid+'.'+mid+'.'+id);
        if(data!=null){
            if(postId!=null){
                JSONObject map=new JSONObject();
                map.put("ID", cid);
                map.put("POSTID", postId);
                JSONObject out=ConditionUtil.getConditionRole(session, map);
                if(out!=null){
                    String state=data.getString("STATE");
                    if(state.indexOf("sent")>=0){
                        if("1".equals(out.getString("AUT_CREATE"))){
                            data.put("sys_sent", "1");
                        }
                        if("1".equals(out.getString("AUT_APPROVE"))){
                            data.put("sys_exec", "1");
                        }
                    } else if(state.indexOf("exec")>=0) {
                        if("1".equals(out.getString("AUT_STOP"))){
                            data.put("sys_stop", "1");
                        }
                    }
                }
            }
        }
        return data;
    }

    private JSONObject queryImpTable(SqlSession session, String impid, String postId) throws RuntimeException {
        try {
            JSONObject json=new JSONObject();
            json.put("IMP_ID", impid);
            SysCondition sysCondition=LocalVariable.getConfig().getSysCondition(session);
            String sql="SELECT * FROM EXE_CONDITION_IMPORT WHERE 1=1 ";
            JSONArray list=session.getForJSON().query(sql, json);

            JSONObject row=list.get(0);
            if(row==null){
                return null;
            }
            row=getDateField(row);
            row=EsbUtil.getConData(row, session, sysCondition);
            row=getDateField(row);
            String cid=row.getString("CONDITION_ID");
            String mid=row.getString("DIMENSION_ID");
            row.remove("CONDITION_ID");
            row.remove("DIMENSION_ID");
            Condition con1= ConditionUtil.getCondition(cid, session);
            json.put("CID", cid);
            json.put("MID", mid);
            row.put("id", row.getString("IMP_ID"));
            ConditionExec exec=new ConditionExec(session, cid);
            String impTab= exec.getimpTabSql(mid, json);
            sql=impTab+" AND A.IMP_STATE=0 ";
            json.remove("autoCompletion");
            //sql=" SELECT * FROM "+tabName+"_EXEC_I A WHERE 1=1 AND A.IMP_STATE=0 ";
            JSONArray slist=new JSONArray();
            session.getForResultSet().sql(sql, json, new QueryCallBackHandler(){
                @Override
                public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                    while(rs.next()){
                        JSONObject mrow=getDateField(rs.toRowJson());
                        mrow=EsbUtil.getConData(mrow, session, sysCondition);
                        slist.add(getDateField(mrow));
                        //slist.add(EsbUtil.getConData(mrow, session, sysCondition));
                    }
                }
            });
            row.put("ITEM_S", slist);
            sql=impTab+" AND A.IMP_STATE>0 ";
            JSONArray flist=new JSONArray();
            session.getForResultSet().sql(sql, json, new QueryCallBackHandler(){
                @Override
                public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                    while(rs.next()){
                        JSONObject mrow=rs.toRowJson();
                        mrow=EsbUtil.getConData(mrow, session, sysCondition);
                        flist.add(getDateField(mrow));
                    }
                }
            });
            row.put("ITEM_F", flist);

            JSONObject j=new JSONObject();
            j.put("ID", cid);
            j.put("NAME", con1.getName());
            row.put("EXE_CONDITION", j);
            j=new JSONObject();
            j.put("ID", mid);
            j.put("NAME", con1.getDimensionById(mid).getName());
            row.put("EXE_DIMENSION", j);
            row.put("innerBusinessType", sBusinessType_imp);
            row.put("innerBusinessKey",row.getString("IMP_ID"));
            if(row!=null){
                if(postId!=null){
                    JSONObject map=new JSONObject();
                    map.put("ID", cid);
                    map.put("POSTID", postId);
                    JSONObject out=ConditionUtil.getConditionRole(session, map);
                    if(out!=null){
                        if("1".equals(out.getString("AUT_CREATE"))){
                            row.put("sys_sent", "1");
                        }
                    }
                }
            }
            return row;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




}
